package com.hzz.web.boss.analysis;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.hzz.api.river.IRiverInfoService;
import com.hzz.dto.analysis.RiverInfoStatDto;
import com.hzz.dto.river.RiverInfoDto;
import com.hzz.dto.user.UserDto;
import com.hzz.framework.PageUtil;
import com.hzz.framework.Response;
import com.hzz.framework.annotation.auth.RequiresPermissions;
import com.hzz.framework.util.DateUtil;
import com.hzz.framework.util.FileUtil;
import com.hzz.framework.util.JwtUtil;
import com.hzz.framework.util.StrUtil;
import com.hzz.framework.util.WebUtil;
import com.hzz.framework.web.controller.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api("河段统计分析")
@RestController
@Slf4j
@RequestMapping("/boss/analysis/riverInfoStat")
public class RiverInfoStatController extends BaseController {
	@Autowired
	private IRiverInfoService riverInfoService;
	@Value("${export.analysis_river_info_treatment}")
	private String templateXls;
	/**
	 * 统计列表分页查询
	 * 
	 * @param dto
	 * @param pageNum
	 * @return
	 */
	@RequiresPermissions("analysis:river:reach")
	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/page/{pageNum}")
	public Response page(@ModelAttribute RiverInfoDto dto, @PathVariable("pageNum") Integer pageNum,
			@RequestParam(required = false) boolean echartsFlag) {
		log.info("page.........");
		Response result = new Response();
		try {
			dto.setPageSize(15);
			if (echartsFlag) {// 调用 者为echarts图表
				UserDto user = JwtUtil.getSubject(UserDto.class);
				Long currAreaId = user.getCurrAreaId();
				if (currAreaId == null) {
					currAreaId = 511025L;// 没有行政区划ID时默认资中县
				}
				dto.setCurrAreaId(currAreaId);
				dto.setPageSize(100);
			}
			dto.setPageNum(pageNum);
			result.data = PageUtil.copy(riverInfoService.statNameNumByParentAreaId(dto));
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	@RequiresPermissions("analysis:river:reach")
	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/statLevelNum")
	public Response<List<RiverInfoStatDto>> statLevelNum() {
		log.info("statLevelNum.........");
		Response result = new Response();
		try {
			UserDto user = JwtUtil.getSubject(UserDto.class);
			Long currAreaId = user.getCurrAreaId();
			if (currAreaId == null) {
				currAreaId = 511025L;// 没有行政区划ID时默认资中县
			}
			result.data = riverInfoService.statLevelNumByParentAreaId(currAreaId);
		} catch (Exception e) {
			result = Response.error(e.getMessage());
		}
		return result;
	}

	@RequiresPermissions("analysis:river:reach")
	@ApiOperation(value = "Excel导出", notes = "Excel导出", code = 200, produces = MediaType.MULTIPART_FORM_DATA_VALUE)
	@PostMapping("/exportExcel")
	public void exportExcel(@ModelAttribute RiverInfoDto dto, HttpServletResponse response,
			HttpServletRequest request) {
		log.info("exportExcel begin>>>>>>>>>{}", dto);
		response.setContentType("application/x-msdownload");
		OutputStream out = null;
		FileInputStream in = null;
		ByteArrayOutputStream bos = null;
		try {
			setResponseHeader(request, response, "河段统计_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");

			// 查询数据
			dto.setPageSize(10000);
			dto.setPageNum(1);
			PageInfo<RiverInfoStatDto> pageInfo = riverInfoService.statNameNumByParentAreaId(dto);
			List<RiverInfoStatDto> datas = pageInfo.getList();
            //创建模板的副本
            InputStream inputStream = FileUtil.getFileAsInputStream(templateXls);
            File temp = new File(System.getProperty("java.io.tmpdir"), "analysis_riverStat_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            FileUtils.copyInputStreamToFile(inputStream, temp);
            //表格s数据填充
            InputStream input = new FileInputStream(temp);
            HSSFWorkbook workBook = new HSSFWorkbook(input);
            Sheet sheet = workBook.getSheetAt(0);
            try {
                for (int i = 0; i < datas.size(); i++) {
                	RiverInfoStatDto data = datas.get(i);
                    //从第2行开始写
                    Row row = sheet.createRow(i + 1);

					row.createCell(0).setCellValue(StrUtil.asString(data.getName()));// 行政区划
                    row.createCell(1).setCellValue(StrUtil.asString(data.getNum1()));// 乡镇级数
                    row.createCell(2).setCellValue(StrUtil.asString(data.getNum2()));// 村级数
                    }
            } catch (Exception e) {
                log.error("excel数据导出填充异常!", e);
            }
            workBook.write(response.getOutputStream());
            workBook.close();
            input.close();
			FileUtil.closeStream(inputStream);
            temp.delete();
            
		} catch (Exception e) {
			log.error("exportExcel error", e);
			WebUtil.sendJson(response, Response.error(500, "excel数据导出异常!" + e.getMessage()));
		}
	}
}
